{% extends 'base.html' %}
{% load static %}

  {% block title %}
  <title>用户添加</title>
  {% endblock title %}
  
  {% block css %}
  <link rel="stylesheet" href="{% static 'ztree/css/zTreeStyle/zTreeStyle.css' %}">
  {% endblock css %}
  
	{% block navheader %}
    <section class="content-header">
      <div class="container-fluid">
        <div class="row mb-1">
          <div class="col-12">
            <ol class="breadcrumb">
              <li class="breadcrumb-item">用户管理</li>
			  <li class="breadcrumb-item"><a href="{% url 'user:users' %}">用户</a></li>
			  <li class="breadcrumb-item active">用户添加</li>
            </ol>
          </div>
        </div>
      </div><!-- /.container-fluid -->
    </section>
	{% endblock navheader %}
	
		  {% block content %}
		  <div class="row">
			  <div class="col-md-6 content-list">
				  <div class="card card-primary">
					<div class="card-header">
					  <h3 class="card-title">必填</h3>
					</div>
					<!-- /.card-header -->
					<div class="card-body row">
						<div class="col-2 pt-1 pb-1">用户名<span style="color:red;"> * </span>：</div><div class="col-10 pt-1 pb-1"><input class="form-control" type="text" id="username" onkeyup="check_username();" onblur="check_newpasswd();"></div>
						<div class="offset-2 col-10 pb-1"><small id="username_error" style="color:red;"></small></div>
						
						<div class="col-2 pt-1 pb-1">密码<span style="color:red;"> * </span>：</div><div class="col-10 pt-1 pb-1"><input type="password" class="form-control" id="newpasswd" onkeyup="check_newpasswd();" onblur="check_newpasswd();" maxlength="256"></div>
						<div class="offset-2 col-10 pb-1"><small id="newpasswd_error" style="color:red;"></small></div>
						
						<div class="col-2 pt-1 pb-1">确认密码<span style="color:red;"> * </span>：</div><div class="col-10 pt-1 pb-1"><input type="password" class="form-control" id="newpasswdagain" onkeyup="check_newpasswdagain();" onblur="check_newpasswdagain();" maxlength="256"></div>
						<div class="offset-2 col-10 pb-1"><small id="newpasswdagain_error" style="color:red;"></small></div>

						<div class="col-2 pt-1 pb-1">昵称<span style="color:red;"> * </span>：</div><div class="col-10 pt-1 pb-1"><input class="form-control" type="text" id="nickname" onkeyup="check_nickname();" onblur="check_nickname();"></div>
						<div class="offset-2 col-10 pb-1"><small id="nickname_error" style="color:red;"></small></div>
						
						<div class="col-2 pt-1 pb-1">邮箱<span style="color:red;"> * </span>：</div><div class="col-10 pt-1 pb-1"><input class="form-control" type="text" id="email" onkeyup="check_email();" onblur="check_email();"></div>
						<div class="offset-2 col-10 pb-1"><small id="email_error" style="color:red;"></small></div>
						
						<div class="col-2 pt-1 pb-2">性别：</div>
						<div class="col-10 pt-1 pb-2">
						  <select class="form-control select2" id="sex" style="width: 100%;">
							<option value="---" selected disabled>请选择性别</option>
							{% for sex in sex_choices %}
							<option value="{{ sex.0 }}">{{ sex.1 }}</option>
							{% endfor %}
						  </select>
						</div>
						<div class="col-2 pt-1 pb-2">角色：</div>
						<div class="col-10 pt-1 pb-2">
						  <select class="form-control select2" id="role" style="width: 100%;">
						    <option value="---" selected disabled>请选择色</option>
							{% for role in role_choices %}
							<option value="{{ role.0 }}">{{ role.1 }}</option>
							{% endfor %}
						  </select>
						</div>
						<div class="offset-2 col-10 pt-1 pb-1">
							<div class="custom-switch custom-switch-on-success">
							  <input type="checkbox" class="custom-control-input" id="enabled" checked>
							  <label class="custom-control-label" for="enabled">启用</label>
							</div>
						</div>
						<div class="offset-2 col-10 pt-2"><a class="btn btn-default" href="{% url 'user:users' %}">返回</a> <button class="btn btn-success ml-2" onclick="changeuserprofile(this);">提交</button><span id="feed_error" class="ml-2" style="color:red;"></span></div>
					</div>
					<!-- /.card-body -->
				  </div>
				  <!-- /.card --> 
			  </div>
			  <div class="col-md-6 content-list">
				  <div class="card card-secondary">
					<div class="card-header">
					  <h3 class="card-title">选填</h3>
					</div>
					<!-- /.card-header -->
					<div class="card-body row">
						<div class="col-2 pt-1 pb-1">手机：</div><div class="col-10 pt-1 pb-1"><input class="form-control" type="text" id="phone" onkeyup="check_phone();" onblur="check_phone();"></div>
						<div class="offset-2 col-10 pb-1"><small id="phone_error" style="color:red;"></small></div>
						
						<div class="col-2 pt-1 pb-1">微信：</div><div class="col-10 pt-1 pb-1"><input class="form-control" type="text" id="weixin" onkeyup="check_weixin();" onblur="check_weixin();"></div>
						<div class="offset-2 col-10 pb-1"><small id="weixin_error" style="color:red;"></small></div>
						
						<div class="col-2 pt-1 pb-1">QQ：</div><div class="col-10 pt-1 pb-1"><input class="form-control" type="text" id="qq" onkeyup="check_qq();" onblur="check_qq();"></div>
						<div class="offset-2 col-10 pb-1"><small id="qq_error" style="color:red;"></small></div>
						
						<div class="col-2 pt-1 pb-1">用户组：</div>
						<div class="col-10 pt-1 pb-1">
						  <div class="form-group">
							<select multiple class="form-control select2_multiple" data-placeholder="请选择用户组" id="group_select_left" style="width:100%">
							  {% for group in all_groups %}
							  <option value="{{ group.id }}">{{ group.group_name }}</option>
							  {% endfor %}
							</select>
						  </div>
						</div>

						<div class="col-2 pt-1 pb-1">主机：</div>
						<div class="col-10 pt-1 pb-1">
						  <div class="form-group">
							<select multiple class="form-control select2_multiple" data-placeholder="请选择主机" id="host_select_left" style="width:100%">
							  {% for host in all_hosts %}
							  <option value="{{ host.id }}">{{ host.hostname }}_{{ host.ip }}_{{ host.remote_user.username }}</option>
							  {% endfor %}
							</select>
						  </div>
						</div>
												
						<div class="col-2 pt-1 pb-1">权限：</div>
						<div class="col-10 pt-1 pb-1">
						  <div class="form-group">
							<ul id="ztree-permissions" class="ztree"></ul>
						  </div>
						</div>
						
						<div class="col-2 pt-1 pb-1">备注：</div><div class="col-10 pt-1 pb-1"><textarea id="memo" class="form-control"></textarea></div>
					</div>
					<!-- /.card-body -->
				  </div>
				  <!-- /.card --> 
			  </div>
		  </div>
		  {% endblock content %}

{% block js %}

<script>
	// 校验表单数据
	check_username = function() {
		var username = $('#username').val();
		if (username == '') {
			$('#username').removeClass("is-valid");
			$('#username').addClass("is-invalid");
			$('#username_error').text('用户名不能未空');
			return false;
		} else if(/[^0-9a-zA-Z\.@]+/g.test(username)) {	// 正则判断
			$('#username').removeClass("is-valid");
			$('#username').addClass("is-invalid");
			$('#username_error').text('用户名必须为数字、字母、@ 或者 .');
			return false;
		} else {
			$('#username').removeClass("is-invalid");
			$('#username').addClass("is-valid");
			$('#username_error').text('');
			return true;
		};
	}

	check_newpasswd = function() {
		var newpasswd = $('#newpasswd').val();
		if (newpasswd == '') {
			$('#newpasswd').removeClass("is-valid");
			$('#newpasswd').addClass("is-invalid");
			$('#newpasswd_error').text('密码不能为空');
			return false;
		} else if(newpasswd.length < 6) {
			$('#newpasswd').removeClass("is-valid");
			$('#newpasswd').addClass("is-invalid");
			$('#newpasswd_error').text('密码长度必须大于等于6个字符');
			return false;
		} else {
			$('#newpasswd').removeClass("is-invalid");
			$('#newpasswd').addClass("is-valid");
			$('#newpasswd_error').text('');
			return true;
		};
	}

	check_newpasswdagain = function() {
		var newpasswd = $('#newpasswd').val();
		var newpasswdagain = $('#newpasswdagain').val();
		if (newpasswdagain == '') {
			$('#newpasswdagain').removeClass("is-valid");
			$('#newpasswdagain').addClass("is-invalid");
			$('#newpasswdagain_error').text('确认密码不能为空');
			return false;
		} else if (newpasswd != newpasswdagain) {
			$('#newpasswdagain').removeClass("is-valid");
			$('#newpasswdagain').addClass("is-invalid");
			$('#newpasswdagain_error').text('两次密码不一致');
			return false;
		} else {
			$('#newpasswdagain').removeClass("is-invalid");
			$('#newpasswdagain').addClass("is-valid");
			$('#newpasswdagain_error').text('');
			return true;
		};
	}

	check_nickname = function() {
		var nickname = $('#nickname').val();
		if (nickname == '') {
			$('#nickname').removeClass("is-valid");
			$('#nickname').addClass("is-invalid");
			$('#nickname_error').text('昵称不能未空');
			return false;
		} else if(/[@#\$%\^&\*]+/g.test(nickname)) {
			$('#nickname').removeClass("is-valid");
			$('#nickname').addClass("is-invalid");
			$('#nickname_error').text('昵称不能存在特殊符号');
			return false;
		}  else if(nickname.length < 3) {
			$('#nickname').removeClass("is-valid");
			$('#nickname').addClass("is-invalid");
			$('#nickname_error').text('昵称长度必须大于等于3个字符');
			return false;
		} else {
			$('#nickname').removeClass("is-invalid");
			$('#nickname').addClass("is-valid");
			$('#nickname_error').text('');
			return true;
		};
	}

	check_email = function() {
		var email = $('#email').val();
		if (email == '') {
			$('#email').removeClass("is-valid");
			$('#email').addClass("is-invalid");
			$('#email_error').text('邮箱不能未空');
			return false;
		} else if(!/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/.test(email)) {
			$('#email').removeClass("is-valid");
			$('#email').addClass("is-invalid");
			$('#email_error').text('邮箱格式不正确');
			return false;
		} else {
			$('#email').removeClass("is-invalid");
			$('#email').addClass("is-valid");
			$('#email_error').text('');
			return true;
		};
	}

	check_phone = function() {
		var phone = $('#phone').val();
		if (phone == '') {
			$('#phone').removeClass("is-invalid");
			$('#phone').removeClass("is-valid");
			//$('#phone').addClass("is-valid");
			$('#phone_error').text('');
			return true;
		} else if(!/^1[3-9][0-9]{9}$/.test(phone)) {
			$('#phone').removeClass("is-valid");
			$('#phone').addClass("is-invalid");
			$('#phone_error').text('手机可为空或者11位正确数字');
			return false;
		} else {
			$('#phone').removeClass("is-invalid");
			$('#phone').addClass("is-valid");
			$('#phone_error').text('');
			return true;
		};
	}

	check_weixin = function() {
		var weixin = $('#weixin').val();
		if (weixin == '') {
			$('#weixin').removeClass("is-invalid");
			$('#weixin').removeClass("is-valid");
			//$('#weixin').addClass("is-valid");
			$('#weixin_error').text('');
			return true;
		} else if(weixin.length < 2) {
			$('#weixin').removeClass("is-valid");
			$('#weixin').addClass("is-invalid");
			$('#weixin_error').text('微信可为空或者大于等于2个字符');
			return false;
		} else {
			$('#weixin').removeClass("is-invalid");
			$('#weixin').addClass("is-valid");
			$('#weixin_error').text('');
			return true;
		};
	}

	check_qq = function() {
		var qq = $('#qq').val();
		if (qq == '') {
			$('#qq').removeClass("is-invalid");
			$('#qq').removeClass("is-valid");
			//$('#qq').addClass("is-valid");
			$('#qq_error').text('');
			return true;
		} else if(!/^[1-9]\d{3,20}$/.test(qq)) {
			$('#qq').removeClass("is-valid");
			$('#qq').addClass("is-invalid");
			$('#qq_error').text('QQ可为空或者4-20位数字');
			return false;
		} else {
			$('#qq').removeClass("is-invalid");
			$('#qq').addClass("is-valid");
			$('#qq_error').text('');
			return true;
		};
	}
	// 校验表单数据

	// 修改用户信息
	changeuserprofile = function(event) {
		toastr.options.closeButton = true;
		toastr.options.showMethod = 'slideDown';
		toastr.options.hideMethod = 'fadeOut';
		toastr.options.closeMethod = 'fadeOut';
		toastr.options.timeOut = 3000;	
		toastr.options.extendedTimeOut = 0;	
		toastr.options.progressBar = true;
		toastr.options.positionClass = 'toast-top-right'; 
		
		$(event).removeAttr("onclick");
		$(event).attr("disabled", true);
		
		var check_right = new Array();
		
		var username = $('#username').val();
		check_right[0] = check_username();

		var newpasswd = $('#newpasswd').val();
		check_right[1] = check_newpasswd();

		var newpasswdagain = $('#newpasswdagain').val();
		check_right[2] = check_newpasswdagain();
		
		var nickname = $('#nickname').val();
		check_right[3] = check_nickname();
		
		var email = $('#email').val();
		check_right[4] = check_email();
		
		var phone = $('#phone').val();
		check_right[5] = check_phone();
		
		var weixin = $('#weixin').val();
		check_right[6] = check_weixin();

		var qq = $('#qq').val();
		check_right[7] = check_qq();

		
		var sex = $("#sex").find("option:selected").val();
		var role = $("#role").find("option:selected").val();
		var memo = $('#memo').val();
		var enabled;
		if ($("#enabled").is(':checked')) {
			enabled = true;
		} else {
			enabled = false;
		}
		
		var groups = new Array();
		$("#group_select_left option:selected").each(function(){
			var value = $(this).val();   //获取option值
			groups.push(value);
		});
		groups = groups.join(",")
		
		var hosts = new Array();
		$("#host_select_left option:selected").each(function(){
			var value = $(this).val();   //获取option值
			hosts.push(value);
		});
		hosts = hosts.join(",")

		var permissions = new Array();
		var treeObj = $.fn.zTree.getZTreeObj("ztree-permissions");
		var nodes = treeObj.getCheckedNodes(true);
		for (let i = 0; i < nodes.length; i++) {
			if (nodes[i].value === undefined) {
				// console.log('-1');
			} else {
				// console.log(nodes[i].value);
				permissions.push(nodes[i].value);
			}
		};
		permissions = permissions.join(",")
		// console.log(permissions)
		
		csrfmiddlewaretoken = '{{ request.COOKIES.csrftoken }}';
		
		if (!/false/.test(check_right)) {
			$('#feed_error').text('');
			$.ajax({
				url: "{% url 'user_api:user_add' %}",
				async: true,
				type: 'POST',
				dataType: 'json',
				data: {
					'csrfmiddlewaretoken': csrfmiddlewaretoken,
					'username': username,
					'newpasswd': newpasswd,
					'newpasswdagain': newpasswdagain,
					'nickname': nickname,
					'email': email,
					'phone': phone,
					'weixin': weixin,
					'qq': qq,
					'sex': sex,
					'memo': memo,
					'enabled': enabled,
					'role': role,
					'groups': groups,
					'hosts': hosts,
					'permissions': permissions,
				},
				timeout: 5000,
				cache: true,
				beforeSend: LoadFunction, //加载执行方法
				error: errFunction,  //错误执行方法
				success: succFunction, //成功执行方法
			});
		} else {
			$('#feed_error').text('信息填写有误，请检查并重新填写');
			$(event).removeAttr("disabled");
			$(event).attr("onclick", "changeuserprofile(this);");
			return false;
		};

		function LoadFunction() {
			// 提交中
		};
		
		function errFunction() {
			// 消息框
			toastr.error('新增用户错误');
			$(event).removeAttr("disabled");
			$(event).attr("onclick", "changeuserprofile(this);");
			return false;
		};
		
		function succFunction(res) {
			if (res.code != 200) {
				// 消息框
				toastr.error('新增用户错误: ' + res.err);
				$(event).removeAttr("disabled");
				$(event).attr("onclick", "changeuserprofile(this);");
				return false;
			} else {
				// 消息框
				toastr.options.timeOut = 1000;
				toastr.options.onHidden = function() { window.location.href = "{% url 'user:users' %}"; }
				toastr.success('新增用户成功');
				return true;
			}
		};
	}

</script>

<script src="{% static 'ztree/js/jquery.ztree.all.min.js' %}"></script>
<script>
	var setting = {
		check: {
			enable: true,
			chkStyle: "checkbox",
			chkboxType: { "Y" : "ps", "N" : "ps" }
		},
		data: {
			simpleData: {
				enable: true
			}
		}
	};

	var zNodes =[
		{
			name: "全部",
			open: true,
			children: {{ ztree_permissions | safe }}
		}
	];

	$(document).ready(function(){
		zTree = $.fn.zTree.init($("#ztree-permissions"), setting, zNodes);
		// zTree.setting.check.chkboxType = { "Y" : "ps", "N" : "ps" };
		//var nodes = zTree.getCheckedNodes(true);
		//console.log(nodes);
	});
	
</script>

{% endblock js %}
